/**
 * 生成唯一文件名
 * @param {Number} len 生成的文件名长度
 * @param {Number} radix 指定基数
 */
function getuuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    var uuid = [];
    var i = 0;
    radix = radix || chars.length

    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'

        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
            }
        }
    }

    return uuid.join('')
}

/**
 * 生成唯一文件名 时间戳 + 随机数
 * @param {Number} len 生成的文件名长度
 * @param {Number} radix 指定基数
 */
function getTimeId(len, radix) {
    if (len) {
        const time = new Date().getTime()
        const uuid = getuuid(len, radix)
        return `${time}${uuid}`
    } else {
        console.log('请输入长度')
    }
}

function resetLargeFileInput(file) {
    file.after(file.clone().val(""));
    file.remove();
}

function syncFileArr(list_container, field_id) {
    var file_arr = [];
    list_container.find('.hkw_file_container').each(function () {
        let furl = $(this).children().first().attr('furl');
        furl && file_arr.push(furl);
    });
    file_arr.length > 0 && $("#" + field_id).val(file_arr.join(','));
    let limit_num = parseInt(list_container.attr('limit_num'));
    if(limit_num > 0 && file_arr.length >= limit_num){
        list_container.find('.add_btn').parent('.hkw_file_container').hide();
    }else{
        list_container.find('.add_btn').parent('.hkw_file_container').show();
    }
}

function appendFileToContainer(list_container, file_url, field_id, img_domain) {
    let ext = file_url.substring(file_url.lastIndexOf('.') + 1);
    let img_exts = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'];
    let video_exts = ['mp4', 'wmv', 'avi', 'mpg', 'mpeg', 'mov', 'rm', 'flv', 'swf'];
    let fname = file_url.substring(file_url.lastIndexOf('/') + 1);
    let full_url = showFullUrl(file_url, img_domain);
    let str = '<div class="hkw_file_container">';
    if (img_exts.indexOf(ext.toLowerCase()) !== -1) {
        //图片
        str += `<img src="${full_url}" furl="${file_url}" />`;
    } else if (video_exts.indexOf(ext.toLowerCase()) !== -1) {
        //视频
        str += `<video src="${full_url}" furl="${file_url}" controls />`;
    } else {
        //其他
        str += `<div class="hkw_file_other" furl="${file_url}">${fname}<\/div>`;
    }
    str += '<div class="delete_file"><\/div><\/div>';
    list_container.append(str);
    syncFileArr(list_container, field_id);
}

function setFileList(list_container, file_arr, field_id, img_domain) {
    file_arr.forEach((v, i) => {
        appendFileToContainer(list_container, v, field_id, img_domain);
    });
}

function showFullUrl(url, img_domain) {
    return window.location.protocol + '//' + img_domain + '/' + url;
}

function hkwFileUpload(container_id, file, uploaderClient, field_id, img_domain) {
    uploaderClient.next = function(percent){
        $("#" + container_id + " .file_progress").show().attr('value', percent).html(percent + '%');
    };
    uploaderClient.error = function(err){
        console.error(err);
    };
    uploaderClient.success = function(url){
        $("#" + container_id + " .file_progress").hide().attr('value', 0).html('0%');
        appendFileToContainer($("#" + container_id + " .file_list"), url, field_id, img_domain);
    };
    uploaderClient.upload(file);
}

function hkwLargeFileInit(container_id, field_id, uploaderClient, img_domain) {
    if ($("#" + field_id).val()) {
        setFileList($("#" + container_id + " .file_list"), $("#" + field_id).val().split(','), field_id, img_domain);
    }
    $(document).undelegate('#' + container_id + ' .delete_file', 'click').delegate('#' + container_id + ' .delete_file', 'click', function () {
        $(this).parent('.hkw_file_container').remove();
        syncFileArr($("#" + container_id + " .file_list"), field_id);
    });
    $(document).undelegate("#" + container_id + " .add_btn", 'click').delegate("#" + container_id + " .add_btn", 'click', function () {
        $("#" + container_id + " .file_input").click();
    });
    $(document).undelegate('#' + container_id + ' .file_input', 'change').delegate('#' + container_id + ' .file_input', 'change', function (e) {
        hkwFileUpload(container_id, e.currentTarget.files[0], uploaderClient, field_id, img_domain);
        resetLargeFileInput($(this));
    });
}
